<template>
  <div class="fund-performance">
    <!-- 顶部标题栏 -->
    <div class="header-bar">
      <div class="header-content">
        <app-logo :small="true" class="header-logo" />
        <div class="back-button" @click="goBack">
          <i class="el-icon-arrow-left"></i> 返回详情
        </div>
      </div>
    </div>
    
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="10" animated />
    </div>
    
    <div v-else-if="fund" class="performance-info">
      <h2>{{ fund.name }} ({{ fund.code }}) - 业绩表现</h2>
      
      <el-tabs v-model="activeTab">
        <el-tab-pane label="收益走势" name="returns">
          <div class="chart-container" ref="returnsChartRef"></div>
        </el-tab-pane>
        <el-tab-pane label="业绩对比" name="comparison">
          <div class="chart-container" ref="comparisonChartRef"></div>
        </el-tab-pane>
      </el-tabs>
      
      <el-descriptions title="业绩统计" :column="3" border>
        <el-descriptions-item label="近一月">{{ performanceData.oneMonth }}%</el-descriptions-item>
        <el-descriptions-item label="近三月">{{ performanceData.threeMonths }}%</el-descriptions-item>
        <el-descriptions-item label="近六月">{{ performanceData.sixMonths }}%</el-descriptions-item>
        <el-descriptions-item label="今年以来">{{ performanceData.ytd }}%</el-descriptions-item>
        <el-descriptions-item label="近一年">{{ performanceData.oneYear }}%</el-descriptions-item>
        <el-descriptions-item label="近三年">{{ performanceData.threeYears }}%</el-descriptions-item>
      </el-descriptions>
    </div>
    
    <div v-else class="error-container">
      <el-empty description="未找到基金业绩数据" />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import axios from 'axios'
import * as echarts from 'echarts'
import AppLogo from '../components/AppLogo.vue'

const route = useRoute()
const router = useRouter()
const fund = ref(null)
const loading = ref(true)
const activeTab = ref('returns')
const returnsChartRef = ref(null)
const comparisonChartRef = ref(null)
let returnsChart = null
let comparisonChart = null

// Sample performance data (will be replaced with API data)
const performanceData = ref({
  oneMonth: 0,
  threeMonths: 0,
  sixMonths: 0,
  ytd: 0,
  oneYear: 0,
  threeYears: 0,
  returnsData: [],
  benchmarkData: []
})

const loadFundPerformance = async () => {
  loading.value = true
  try {
    // Load fund details
    const fundResponse = await axios.get(`/api/funds/${route.params.id}`)
    fund.value = fundResponse.data.fund
    
    // Load performance data
    const performanceResponse = await axios.get(`/api/funds/${route.params.id}/performance`)
    performanceData.value = performanceResponse.data
    
    // Initialize charts after data is loaded
    nextTick(() => {
      initCharts()
    })
  } catch (error) {
    console.error('Failed to load fund performance:', error)
    ElMessage.error('加载基金业绩数据失败')
  } finally {
    loading.value = false
  }
}

const initCharts = () => {
  // Initialize returns chart
  if (returnsChartRef.value) {
    returnsChart = echarts.init(returnsChartRef.value)
    const returnsOption = {
      title: {
        text: '净值走势'
      },
      tooltip: {
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        data: performanceData.value.returnsData.map(item => item.date)
      },
      yAxis: {
        type: 'value',
        name: '净值'
      },
      series: [{
        name: '净值',
        type: 'line',
        data: performanceData.value.returnsData.map(item => item.value),
        smooth: true
      }]
    }
    returnsChart.setOption(returnsOption)
  }
  
  // Initialize comparison chart
  if (comparisonChartRef.value) {
    comparisonChart = echarts.init(comparisonChartRef.value)
    const comparisonOption = {
      title: {
        text: '业绩对比'
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: ['本基金', '基准']
      },
      xAxis: {
        type: 'category',
        data: performanceData.value.returnsData.map(item => item.date)
      },
      yAxis: {
        type: 'value',
        name: '收益率(%)'
      },
      series: [
        {
          name: '本基金',
          type: 'line',
          data: performanceData.value.returnsData.map(item => item.returnRate),
          smooth: true
        },
        {
          name: '基准',
          type: 'line',
          data: performanceData.value.benchmarkData.map(item => item.returnRate),
          smooth: true
        }
      ]
    }
    comparisonChart.setOption(comparisonOption)
  }
}

const goBack = () => {
  router.push({ name: 'fundDetail', params: { id: route.params.id } })
}

// Handle tab changes to resize charts
watch(activeTab, () => {
  nextTick(() => {
    if (activeTab.value === 'returns' && returnsChart) {
      returnsChart.resize()
    } else if (activeTab.value === 'comparison' && comparisonChart) {
      comparisonChart.resize()
    }
  })
})

// Handle window resize
window.addEventListener('resize', () => {
  if (returnsChart) returnsChart.resize()
  if (comparisonChart) comparisonChart.resize()
})

onMounted(() => {
  loadFundPerformance()
})

// Clean up charts when component is unmounted
onUnmounted(() => {
  if (returnsChart) returnsChart.dispose()
  if (comparisonChart) comparisonChart.dispose()
  window.removeEventListener('resize', () => {})
})
</script>

<style scoped>
.fund-performance {
  min-height: 100vh;
  background-color: #fff;
}

.header-bar {
  background-color: #8086fd;
  color: white;
  padding: 15px 0;
  text-align: center;
  position: relative;
}

.header-bar h1 {
  margin: 0;
  font-size: 22px;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  align-items: center;
  position: relative;
}

.back-button {
  color: white;
  cursor: pointer;
  margin-left: 20px;
}

.header-logo {
  margin-right: 10px;
}

.loading-container, .error-container {
  max-width: 1000px;
  margin: 40px auto;
  padding: 0 20px;
}

.performance-info {
  max-width: 1000px;
  margin: 20px auto;
  padding: 0 20px;
}

.chart-container {
  width: 100%;
  height: 400px;
  margin: 20px 0;
}
</style>